// BlWtlUI.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"

#include "MainFrm.h"

CAppModule _Module;
BOOL APIENTRY DllMain( HANDLE hModule, 
                       DWORD  ul_reason_for_call, 
                       LPVOID lpReserved
					 )
{
    return TRUE;
}

class CBlApp
{
public:
	CBlApp(){}
	~CBlApp(){}
private:
	int pvWtlRun(LPTSTR /*lpstrCmdLine*/ = NULL, int nCmdShow = SW_SHOWDEFAULT)
	{ 
		HANDLE hExclusion = NULL;   // used to detect another running instance
		hExclusion = CreateMutex(NULL, FALSE, "{8FA6E763-BF01-4db0-AFC3-FA53ED373513}");
		
		if ( GetLastError() == ERROR_ALREADY_EXISTS )
		{
			// The mutex already exists, bring the running instance to top
			
			HWND hWndPrev, hWndChild;
			
			// Determine if another window with your class name exists...
			if (hWndPrev = ::FindWindow("BeautifulloverWTL", NULL))
			{
				// If so, does it have any popups?
				hWndChild = ::GetLastActivePopup(hWndPrev);
				
				// If iconic, restore the main window
				if (::IsIconic(hWndPrev))
					::ShowWindow(hWndPrev, SW_RESTORE);
				
				// Bring the main window or its popup to
				// the foreground
				::SetForegroundWindow(hWndChild);
				
				// now the previous instance is activated 
				return 0;
			}
		}
		
		CMessageLoop theLoop;
		_Module.AddMessageLoop(&theLoop);
		
		CMainFrame xdWndMain;
		
		if(xdWndMain.CreateEx() == NULL)
		{
			printf(_T("Main window creation failed!\n"));
			return 0;
		}
		
		xdWndMain.ShowWindow(nCmdShow | SW_SHOWNORMAL);
		
		int nRet = theLoop.Run();
		
		_Module.RemoveMessageLoop();
		if ( hExclusion != NULL )
			CloseHandle(hExclusion);
		
		return nRet;
	}
	   

public:		
	BLSTATUS _wtlMain()
	{ 	
		printf(_T("wtlMain: \n"));
		HRESULT hRes = ::CoInitialize(NULL); 
		ATLASSERT(SUCCEEDED(hRes)); 
		::DefWindowProc(NULL, 0, 0, 0L);
		
		AtlInitCommonControls(ICC_COOL_CLASSES | ICC_BAR_CLASSES); 
		HINSTANCE hInstance = GetModuleHandle(NULL); 
		hRes = _Module.Init(NULL, hInstance);
		ATLASSERT(SUCCEEDED(hRes));
		
		int nRet = pvWtlRun(NULL, NULL);
		
		_Module.Term();
		::CoUninitialize();
		return  BL_STATUS_OK;
	}
		
		
};
extern "C" BLSTATUS __stdcall OnBlApi(HWND hWnd,UINT uM, WPARAM wP, LPARAM lP)
{	
	BLSTATUS	r = BL_STATUS_NOT_SUPPORT_INTERFACE;   
	CBlApp a; 	
	r = a._wtlMain();
	return r;
}